import com.devops.StageResult
import groovy.transform.CompileStatic
import org.jenkinsci.plugins.workflow.cps.CpsScript

// 存储脚本上下文和阶段结果
private CpsScript script
private List<Map> stageResults = []
// 跟踪当前stage是否实际执行
private boolean isStageExecuted = false

@CompileStatic
def enable(CpsScript scriptContext) {
    // 初始化存储
    this.script = scriptContext
    this.stageResults = []
    
    // 替换默认的stage方法，实现拦截
    replaceStageMethod(scriptContext)
}

def saveToDatabase(Map config = [:]) {
    println "Call saveToDatabase method"
    try {
        //获取Failure stage信息
        def failureStage = getFailureStage()
        println "Failure Stage: name = ${failureStage.name}, message: ${failureStage.errorMessage}"

        def reporter = new com.devops.PipelineReporter(this)
        reporter.updateFailureInfo(failureStage.name, failureStage.errorMessage)
        reporter.reportPipelineStatus()
    }catch (Exception e) {
        println "Error saving to database: ${e.message}"
    }
}

def getFailureStage() {
    try {
        if (stageResults.isEmpty()) {
            script.echo "No stage results recorded"
            return new StageResult(name: "", errorMessage: "")
        }
        
        // 查找第一个失败的阶段
        for (Map resultMap : stageResults) {
            if (resultMap.get('status') == 'FAILURE') {
                def result = new StageResult(
                    name: resultMap.get('name', 'Unknown'),
                    status: resultMap.get('status', 'Unknown'),
                    errorMessage: resultMap.get('errorMessage')
                )
                
                return result
            }
        }
        
        return new StageResult(name: "", errorMessage: "")
    } catch (Exception e) {
        script.echo "Error generating stage report: ${e.getMessage()}"
        e.printStackTrace()
        return new StageResult(name: "", errorMessage: "")
    } 
}

// 替换默认的stage方法以实现拦截
private void replaceStageMethod(CpsScript script) {
    script.metaClass.stage = { String name, Closure body ->
        def status = "SUCCESS"
        def errorMessage = null
        isStageExecuted = false // 重置执行状态
        
        try {
            // 在执行stage体之前标记为已执行
            isStageExecuted = true
            // 调用原始stage方法
            return script.invokeMethod("stage", [name, body] as Object[])
        } catch (Exception e) {
            status = "FAILURE"
            // 获取更详细的错误信息，包括命令执行的输出
            errorMessage = extractDetailedErrorMessage(e)
            script.echo "Error executing stage '${name}': ${errorMessage}"
            e.printStackTrace()
            throw e // 继续抛出异常，不影响原有流水线的失败处理
        } finally {
            try {
                // 只记录实际执行的stage
                if (isStageExecuted) {
                    stageResults.add([
                        name: name,
                        status: status,
                        errorMessage: errorMessage
                    ])
                }
            } catch (Exception e) {
                script.echo "Error recording stage result: ${e.getMessage()}"
                e.printStackTrace()
            }
        }
    }
}

// 提取详细的错误信息
private String extractDetailedErrorMessage(Exception e) {
    // 尝试从多种可能的异常类型中获取详细错误信息
    if (e.getCause() != null) {
        def cause = e.getCause()
        // 如果是hudson.AbortException，尝试获取更深层的错误信息
        if (cause.getClass().getSimpleName().contains("AbortException")) {
            if (cause.getMessage() != null) {
                return cause.getMessage()
            }
        }
        
        // 尝试获取cause的详细信息
        if (cause.getMessage() != null) {
            return cause.getMessage()
        }
    }
    
    // 检查异常本身是否有详细信息
    if (e.getMessage() != null) {
        return e.getMessage()
    }
    
    // 最后返回默认信息
    return e.toString()
}